package com.jichaoyun.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.dao.app.mapper.AppUserMapper;
import com.jichaoyun.dao.mapper.*;
import com.jichaoyun.model.app.AppUser;
import com.jichaoyun.model.entity.FlowHour;
import com.jichaoyun.model.entity.RealdataCache;
import com.jichaoyun.model.entity.StationInfo;
import com.jichaoyun.model.entity.User;
import com.jichaoyun.model.vo.RollVo;
import com.jichaoyun.model.vo.SmartMapVo;
import com.jichaoyun.service.IRealdataCacheService;
import com.jichaoyun.service.IStationInfoService;
import com.jichaoyun.service.util.TcpUtils.TcpConnect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@RestController
@Api(tags = {"智慧大屏相关的接口"})
@RequestMapping("/sys/bigScreen")
@Slf4j
public class BigScreenController {

    @Autowired
    private FlowHourMapper flowHourMapper;

    @Autowired
    private FlowDayMapper flowDayMapper;

    @Autowired
    private StationInfoMapper stationInfoMapper;

    @Autowired
    private RealdataMapper realdataMapper;

    @Autowired
    private IRealdataCacheService realdataCacheService;

    @Autowired
    private IStationInfoService stationInfoService;

    @Autowired
    private RealdataCacheMapper realdataCacheMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private StationInfoWaterMapper stationInfoWaterMapper;

    @ApiOperation("供汽总量月同比分析")
    @GetMapping("/getSteamMonthlyTB")
    private Result<Map<String, List>> getSteamMonthlyTB(){
        HashMap<String, List> resmap = new HashMap<>();
        LocalDateTime theMonthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withDayOfMonth(25).withHour(9).withMinute(0).withSecond(0).withNano(0);
        theMonthStart = theMonthStart.minusMonths(11);
        ArrayList<String> monthsList = new ArrayList<>();
        ArrayList<Float> flowList = new ArrayList<>();
        ArrayList<Float> lastYearFlowList = new ArrayList<>();

        //查找所有的站点
        LambdaQueryWrapper<StationInfo> wp = new LambdaQueryWrapper<>();
        wp/*.eq(StationInfo::getUserType,2)*/
                .in(StationInfo::getStationNo, Arrays.asList(324,317,320,319,322,321));
        List<StationInfo> stationInfos = stationInfoMapper.selectList(wp);

        for(int i=0;i<12;i++){
            monthsList.add(theMonthStart.getMonthValue()+"月");
            Float flow = 0f,last_flow =0f;
            for (StationInfo stationInfo : stationInfos) {
                if (stationInfo.getStationNo() != 317){
                    flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart) * 1.05f;//除中科外均要乘以5%的管损
                    last_flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart.minusMonths(12)) * 1.05f;
                }else {
                    flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart);//中科不做处理
                    last_flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart.minusMonths(12));
                }
            }
            flowList.add(flow);
            lastYearFlowList.add(last_flow);
            theMonthStart = theMonthStart.plusMonths(1);
        }
        resmap.put("最近12个月数据",flowList);
        resmap.put("同比12个月数据",lastYearFlowList);
        resmap.put("月份坐标",monthsList);
        return Result.success(resmap);

    }

    @ApiOperation("供汽总量月环比分析")
    @GetMapping("/getSteamMonthlyHB")
    private Result<Map<String, List>> getSteamMonthlyHB(){
        HashMap<String, List> resmap = new HashMap<>();
        LocalDateTime theMonthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withDayOfMonth(25).withHour(9).withMinute(0).withSecond(0).withNano(0);
        theMonthStart = theMonthStart.minusMonths(11);
        ArrayList<String> monthsList = new ArrayList<>();
        ArrayList<Float> flowList = new ArrayList<>();
        ArrayList<Float> lastYearFlowList = new ArrayList<>();

        //查找所有的站点
        LambdaQueryWrapper<StationInfo> wp = new LambdaQueryWrapper<>();
        wp/*.eq(StationInfo::getUserType,2)*/
                .in(StationInfo::getStationNo, Arrays.asList(324,317,320,319,322,321));
        List<StationInfo> stationInfos = stationInfoMapper.selectList(wp);

        for(int i=0;i<12;i++){
            monthsList.add(theMonthStart.getMonthValue()+"月");
            Float flow = 0f,last_flow =0f;
            for (StationInfo stationInfo : stationInfos) {
                if (stationInfo.getStationNo() != 317){
                    flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart) * 1.05f;//除中科外均要乘以5%的管损
                    last_flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart.minusMonths(1)) * 1.05f;
                }else {
                    flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart);//中科不做处理
                    last_flow+= getSettleFlowByMonth(stationInfo.getStationNo(),theMonthStart.minusMonths(1));
                }
            }
            flowList.add(flow);
            lastYearFlowList.add(last_flow);
            theMonthStart = theMonthStart.plusMonths(1);
        }
        resmap.put("最近12个月数据",flowList);
        resmap.put("环比12个月数据",lastYearFlowList);
        resmap.put("月份坐标",monthsList);
        return Result.success(resmap);

    }

    @ApiOperation("低压蒸汽价格趋势")
    @GetMapping("/getPriceMonthly")
    private Result<Map<String, List>> getPriceMonthly(){
        //目前使用excel文件去获取过去月份的汽价
        HashMap<String, List> resMap = new HashMap<>();
        String filePath = "C:\\Users\\Administrator\\Desktop\\往月汽价.xlsx";//excel绝对路径
        ExcelReader reader = ExcelUtil.getReader(filePath);
        List<Map<String, Object>> maps = reader.readAll();
        ArrayList<String> monthsList = new ArrayList<>();
        ArrayList<Float> priceList = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            monthsList.add((String) map.get("月份"));
            priceList.add(Float.valueOf(map.get("价格").toString())) ;
        }

        resMap.put("最近12个月的价格趋势",priceList);
        resMap.put("月份坐标",monthsList);
        reader.close();
        return Result.success(resMap);
/*        LocalDateTime theMonthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
        theMonthStart = theMonthStart.minusMonths(11);
        ArrayList<String> monthsList = new ArrayList<>();
        ArrayList<Float> priceList = new ArrayList<>();

        //查找所有的站点
        Integer stationNo = stationInfoMapper.selectFirstSteamOne().getStationNo();

        for(int i=0;i<12;i++){
            monthsList.add(theMonthStart.getMonthValue()+"月");
            FlowHour flowHour = flowHourMapper.selectRecentOneByStationPeriod(stationNo,theMonthStart,theMonthStart.plusDays(30));
//            Realdata realdata= realdataMapper.historySelectOne(stationNo, theMonthStart, theMonthStart.plusDays(30));
            if (flowHour==null){
                priceList.add(0f);
            }else {
                priceList.add(flowHour.getFeeHour().floatValue());
            }
            theMonthStart = theMonthStart.plusMonths(1);
        }*/


    }

    @ApiOperation("查询数据，30分钟曲线，查询近30分钟数据")
    @GetMapping("/getHalfHourRealData")
    public Result<Map<String,List>> getHalfHourRealData() {
        return Result.success(realdataCacheService.getHalfHourTotalRealData());
    }
    @ApiOperation("查询数据，24小时曲线，查询近24小时数据")
    @GetMapping("/get24HourRealData")
    public Result<Map<String,List>> get24HourRealData() {
        return Result.success(realdataCacheService.get24HourRealData());
    }

    @ApiOperation("查询大屏中下的滚动实时信息")
    @GetMapping("/getRollRealData")
    public Result<List<RollVo>> getRollRealData() {
        ArrayList<RollVo> res = new ArrayList<>();
        //对蒸汽站点的判断
        List<StationInfo> allUsedStationInfo = stationInfoService.getAllUsedStationInfo();
        for (StationInfo stationInfo : allUsedStationInfo) {
            RollVo rollVo = new RollVo();
            rollVo.setName(stationInfo.getStationName());
            RealdataCache cache = realdataCacheService.getStationSingleInfoById(stationInfo.getStationNo());
            if(cache==null){
                rollVo.setIsOnline("离线");
                res.add(rollVo);
                continue;
            }
            if(TcpConnect.isOnLine[stationInfo.getStationNo()]){
                rollVo.setIsOnline("在线");
            }else{
                rollVo.setIsOnline("离线");
                res.add(rollVo);
                continue;
            }
            rollVo.setFlow(cache.getFlow());
            rollVo.setPres(cache.getPres());
            rollVo.setTemp(cache.getTemp());
            rollVo.setTotal(cache.getTotal());
            rollVo.setFAlarm(cache.getFAlarm());
            rollVo.setPlAlarm(cache.getPlAlarm());
            rollVo.setTAlarm(cache.getTAlarm());
            rollVo.setVAlarm(cache.getVAlarm());
            res.add(rollVo);
        }


        return Result.success(res);
    }


    @ApiOperation("查询最大片区(湾塘）的实时管损")
    @GetMapping("/getPipeLoss")
    public Result<String> getPipeLoss(){
        LambdaQueryWrapper<StationInfo> mains_wp = new LambdaQueryWrapper<>();
        mains_wp.eq(StationInfo::getUserType,0).eq(StationInfo::getLineId,1);
        List<StationInfo> mains = stationInfoMapper.selectList(mains_wp);
        LambdaQueryWrapper<StationInfo> sub_wp = new LambdaQueryWrapper<>();
        sub_wp.eq(StationInfo::getUserType,1).eq(StationInfo::getLineId,1);
        List<StationInfo> subs = stationInfoMapper.selectList(sub_wp);
        float total_main = 0f;
        float total_sub = 0f;
        for (StationInfo main : mains) {
            RealdataCache realdataCache = realdataCacheMapper.selectRecentOneByStation(main.getStationNo());
            if(realdataCache!=null){
                total_main+=realdataCache.getFlow();
            }
        }
        for (StationInfo sub : subs) {
            RealdataCache realdataCache = realdataCacheMapper.selectRecentOneByStation(sub.getStationNo());
            if(realdataCache!=null){
                total_sub+=realdataCache.getFlow();
            }
        }
        if((total_main+total_sub)!=0)
            return Result.success(String.format("%.2f",(total_main-total_sub)*100/(total_main)));
        else
            return Result.success(0+"");
    }

    @ApiOperation("片区用量分析")
    @GetMapping("/getPianQu")
    public Result<Map<String,Float>> getPianQu(){
        HashMap<String, Float> res = new HashMap<>();
        Float [] acc = {0f,0f,0f};
        Float [] rate = {0f,0f,0f};
        for (int i=1;i<=3;i++){
            LambdaQueryWrapper<StationInfo> wp = new LambdaQueryWrapper<>();
            wp.eq(StationInfo::getLineId,i).eq(StationInfo::getUserType,0);
            List<StationInfo> stationInfos = stationInfoMapper.selectList(wp);
            for (StationInfo stationInfo : stationInfos) {
                RealdataCache cache = realdataCacheMapper.getStationSingleInfoById(stationInfo.getStationNo());
                if(cache!=null && cache.getFlow()!=null) {
                    acc[i-1] += cache.getFlow();
                    continue;
                }
                acc[i-1] += 0;
            }
        }
//        rate[0] = acc[0]/(acc[0]+acc[1]+acc[2]);
//        rate[1] = acc[1]/(acc[0]+acc[1]+acc[2]);
//        rate[2] = acc[2]/(acc[0]+acc[1]+acc[2]);
        res.put("湾塘片",acc[0]);
        res.put("澥浦片",acc[1]);
        res.put("龙山片",acc[2]);

        return Result.success(res);
    }


    @ApiOperation("智慧地图根据公司的名字获取相应站点的信息")
    @GetMapping("/getCompanyInfoByName")
    public Result<SmartMapVo> getAllStationReal(String name){
//        //根据公司名查用户
//        LambdaQueryWrapper<User> wp = new LambdaQueryWrapper<>();
//        wp.eq(User::getCompanyName,name.trim());
//        User user = userMapper.selectOne(wp);
//        LambdaQueryWrapper<StationInfo> wp1 = new LambdaQueryWrapper<>();
//        List<StationInfo> stationInfos = new ArrayList<>();
//        AppUser appUser = new AppUser();
//        if(user == null){
//            LambdaQueryWrapper<AppUser> wp0 = new LambdaQueryWrapper<>();
//            wp0.eq(AppUser::getCompanyName,name.trim());
//            appUser = appUserMapper.selectOne(wp0);
//
//             wp1.eq(StationInfo::getAppUserId,appUser.getId());
//            stationInfos = stationInfoMapper.selectList(wp1);
//        }else {
//            //根据用户查询站点信息
//            wp1.eq(StationInfo::getUserId,user.getId());
//            stationInfos = stationInfoMapper.selectList(wp1);
//        }
        //根据站点名查站点信息
        LambdaQueryWrapper<StationInfo> wp1 = new LambdaQueryWrapper<>();
        wp1.eq(StationInfo::getStationName,name.trim());
        List<StationInfo> stationInfos = stationInfoMapper.selectList(wp1);
        //根据站点号查询相应数据
        Float flow=0f ,temp=0f,pres =0f,total=0f,caliber=0f;
        BigDecimal balance = BigDecimal.ZERO;
        for (StationInfo stationInfo : stationInfos) {
            RealdataCache cache = realdataCacheMapper.selectRecentOneByStation(stationInfo.getStationNo());
            flow+=cache.getFlow();
            temp+=cache.getTemp();
            pres+=cache.getPres();
            balance=balance.add(cache.getBalance());
            total+=cache.getTotal();
           // caliber+=cache.getCaliber();
        }
        SmartMapVo smartMapVo = new SmartMapVo();
        smartMapVo.setCompanyName(name);
        smartMapVo.setFlow(flow/stationInfos.size());
        smartMapVo.setPres(pres/stationInfos.size());
        smartMapVo.setTemp(temp/stationInfos.size());
        smartMapVo.setBalance(balance.divide(BigDecimal.valueOf(stationInfos.size()), 2, RoundingMode.HALF_UP));
        smartMapVo.setTotal(total/stationInfos.size());
        smartMapVo.setCaliber(stationInfos.get(0).getCaliber());
        return Result.success(smartMapVo);
    }

    /**
     * 获取某月实际用了多少流量(精确到小时)
     * @param station_no
     * @param start
     * @return
     */
    private Float getSettleFlowByMonth(Integer station_no, LocalDateTime start) {

        LocalDateTime startOfDayTime = start;
        LocalDateTime endOfDayTime = start.plusMonths(1);

        LambdaQueryWrapper<FlowHour> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowHour::getStation,station_no)
                .ge(FlowHour::getRecStart,startOfDayTime)
                .le(FlowHour::getRecStart,endOfDayTime)
                .orderByAsc(FlowHour::getId);
        List<FlowHour> flowHourList = flowHourMapper.selectList(wrapper);

        if(flowHourList==null|| flowHourList.size()==0){
            return 0f;
        }
        return  flowHourList.get(flowHourList.size()-1).getFStart() - flowHourList.get(0).getFStart();
    }

    @ApiOperation("行业用气量分析")
    @GetMapping("/getIndustryData")
    private Result<Map<String, Object>> getIndustryData(){
        return Result.success(realdataCacheService.getIndustryData());
    }
}